//
//  CLLNewFeatureView.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/13.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

// 设置常量
let count = 4
let rect = UIScreen.main.bounds
class CLLNewFeatureView: UIView {

    /// 属性
    /// scrollview
    @IBOutlet weak var scrollView: UIScrollView!
    /// 进入按钮
    @IBOutlet weak var enterButton: UIButton!
    /// pageControl
    @IBOutlet weak var pageControl: UIPageControl!
    
    /// 进入欢迎界面的类方法
    class func newFeature() -> CLLNewFeatureView {
        
        let nib = UINib(nibName: "CLLNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! CLLNewFeatureView
        
        return v
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
       
        // 加载欢迎视图的图片
        
        for i in 0..<count {
            
            let imageView = UIImageView(image: UIImage(named: "new_feature_\(i + 1)"))
            imageView.frame = rect.offsetBy(dx: rect.width * CGFloat(i), dy: 0)
            
            scrollView.addSubview(imageView)
        }
        
        // 设置scrollview属性
        setUpScrollView()
        
    }

    /// 按钮点击事件
    @IBAction func enterButtonClick(_ sender: Any) {
        self.removeFromSuperview()
    }
}
// MARK: - 设置scrollview相关
extension CLLNewFeatureView {
    
    fileprivate func setUpScrollView () {
        
        // 设置scrollview的属性
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.delegate = self
        
        // 隐藏enterbutton
        enterButton.isHidden = true
    }
    
}

// MARK: - UIScrollViewDelegate
extension CLLNewFeatureView :UIScrollViewDelegate {
 
    /// 根据scrollview滚动的位置来设置pageControl的显示
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 计算page页数
        let page = Int(scrollView.contentOffset.x / UIScreen.hm_screenWidth() + 0.5)
        // 设置pageControl的值
        pageControl.currentPage = page
        // 隐藏pageControl
        pageControl.isHidden = (page == scrollView.subviews.count)
        // 显示enterbutton
        if page ==  scrollView.subviews.count - 1 {
            enterButton.isHidden = false
        }
        // 移除新特性界面
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
    }
    
    
}
